<?php
namespace wx;
class Wechat{ 
    private $postObj;
    private $fromUsername;
    private $toUsername;
    private $keyword;
    private $event;
    private $type;
public function valid()
    {
        $echoStr = $_GET["echostr"];

       
        if($this->checkSignature())
        {
        	echo $echoStr;
        	exit;
        }
    }
    
    public function __construct($token){
        define("TOOKEN", $token);
    }
    public function responseMsg(){
//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //如果我们用户没有发送消息 给微信服务器就不处理只有
        //用户通过微信客户端发送文本..信息我们接受原生微信服务器
        //发送的xml字符串信息
        if(!empty($postStr)){
            libxml_disable_entity_loader(true);
            $postObj=simplexml_load_string($postStr);
           return $postObj;
        }
    }
    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
    
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
    
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
    
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}